using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DiceManagingScript : MonoBehaviour
{
    private readonly List<GameObject> dices = new List<GameObject>();
    public DiceSettings Settings;
    public GameObject DiceTemplate;

    private void OnEnable()
    {
        var template = Instantiate(DiceTemplate);
        template.SetActive(true);

        var scale = template.transform.localScale;
        scale *= Settings.Scale;
        scale.x *= Settings.DiameterToHeight;
        scale.z *= Settings.DiameterToHeight;
        template.transform.localScale = scale;

        for (int i = 0; i < Settings.Count; i++)
        {
            var newDice = Instantiate(template);
            newDice.GetComponent<Renderer>().material.color = Random.ColorHSV();
            dices.Add(newDice);
        }

        Destroy(template);
    }

    public void TossAll()
    {
        foreach (var dice in dices)
        {
            float RandomBetween(float a, float b)
            {
                if (a < b)
                    return Random.Range(a, b);
                return Random.Range(b, a);
            }

            dice.transform.SetPositionAndRotation(
                new Vector3(
                    RandomBetween(Settings.RegionStarting.x, Settings.RegionEnding.x),
                    RandomBetween(Settings.RegionStarting.y, Settings.RegionEnding.y),
                    RandomBetween(Settings.RegionStarting.z, Settings.RegionEnding.z)),
                Random.rotationUniform);
        }
    }

    public (int side, int headOrTail, int neither) GetFaceToGround(float delta = 5F)
    {
        int[] result = new int[3];
        foreach (var dice in dices)
        {
            int currentResult = 0;
            // 0: neither, 1: headOrTail, 2: side

            var difference = dice.transform.rotation.eulerAngles.z;
            if (difference > 180F - delta)
                difference -= 180F;

            if (-delta < difference && difference < delta)
                currentResult = 1;

            difference -= 90F;
            if (-delta < difference && difference < delta)
                currentResult = currentResult is 1 ? 0 : 2;

            result[currentResult] = result[currentResult] + 1;
        }
        return (result[2], result[1], result[0]);
    }

    private void OnDisable()
    {
        foreach(var dice in dices)
            Destroy(dice);
    }
}
